use serde::{Deserialize, Deserializer};
use std::{fmt::Display, str::FromStr};

#[derive(Deserialize)]
#[serde(untagged)] // 序列化时会一个一个去尝试看匹配到符合的类型
enum StringOrNumber<T> {
  String(String),
  Number(T),
}

// 为了序列化的时候数字和字符数字兼容
pub fn deserialize_number<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
  T: FromStr + Deserialize<'de>,
  T::Err: Display,
  D: Deserializer<'de>,
{
  match StringOrNumber::deserialize(deserializer)? {
    StringOrNumber::String(s) => s.parse().map_err(serde::de::Error::custom),
    StringOrNumber::Number(n) => Ok(n),
  }
}
